/**
 * Copyright (C), 2020-2020, 软件公司
 * FileName: NewsController
 * Author:   cakin
 * Date:     2020/5/5
 * Description: 新闻控制器
 */
package com.cakin.newssystem.core.controller;

import com.cakin.newssystem.common.RequestException;
import com.cakin.newssystem.common.ResponseCode;
import com.cakin.newssystem.common.ResponseResult;
import com.cakin.newssystem.core.dto.NewsDTO;
import com.cakin.newssystem.core.entity.News;
import com.cakin.newssystem.core.service.NewsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;

/**
 * @ClassName: NewsController
 * @Description: 新闻控制器
 * @Date: 2020/5/5
 * @Author: cakin
 */
@RestController
@RequestMapping(value = {"/news"})
@Slf4j
public class NewsController {

    /**
     * 新闻服务
     */
    @Autowired
    private NewsService newsService;

    /**
     * 查询新闻列表
     *
     * @param username 用户名
     * @return ResponseResult 返回给前端的消息
     */
    @GetMapping(value = {"/list"})
    public ResponseResult listNews( @RequestParam("username") String username ) {
        List<News> news = newsService.list(username);
        return ResponseResult.e(ResponseCode.OK, news);
    }

    @PostMapping(value = {"/add"})
    public ResponseResult addNews( @RequestBody NewsDTO newsDTO ) {
        try {
            newsService.add(newsDTO);
            return ResponseResult.e(ResponseCode.OK, "");
        } catch (RequestException e) {
            if (e.getStatus() == ResponseCode.SQL_FAIL.getCode()) {
                return ResponseResult.e(ResponseCode.SQL_FAIL, "");
            }
            return ResponseResult.e(ResponseCode.FAIL, "");
        }
    }

    @GetMapping(value = {"/detail"})
    public ResponseResult detailNews( @RequestParam("username") String username,
                                      @RequestParam("title") String title ) {
        try {
            News news = newsService.detail(username, title);
            return ResponseResult.e(ResponseCode.OK, news);
        } catch (RequestException e) {
            if (e.getStatus() == ResponseCode.TOO_MANY_RESULTS.getCode()) {
                return ResponseResult.e(ResponseCode.TOO_MANY_RESULTS, "");
            }
            return ResponseResult.e(ResponseCode.FAIL, "");
        }
    }
}
